#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "mysql_util.h"
#include "sysinfo.h"

int getSysInfo(sysInfo_type *sysinfo){
	char hostname[128] = {0};
	if(sysinfo == NULL)
	{
		printf("sysinfo is NULL!!\n");
		return -1;
	}
	/*get host name*/
	gethostname(hostname,sizeof(hostname));
	memcpy(sysinfo->hostname,hostname,sizeof(hostname));
	/*get cpu usage*/
	getCpuUsage(&sysinfo->cpu_usage);

	/*get mem usage*/

	getMemInfo(&sysinfo->mem_usage);
	
	/*get disk usage*/
	getDiskInfo(&sysinfo->disk_use);

	return 0;

}
int main(void) 
{
	int ret = 0;
	sysInfo_type s = {0};
	if (init_mysql())
	{
		print_mysql_error(NULL);
		return -1;
	}
	
	printf("INIT MYSQL OK\nNow start acq the system info\n");
	
	while(1)
	{
		memset(&s,0x00,sizeof(s));
		ret = getSysInfo(&s);
		if(ret != 0)
		{
			printf("Get system info failed!!\n");
			continue;
		}
		
		printf("Hostname:%s;\n",s.hostname);
		printf("cpu usage: %s %.01f us, %.01f sy, %.01f ni, %.01f id, %.01f wa, %.01f hi, %.01f si, %.01f st\n",
			//"%s: us:%.02f sy:%.02f ni:%.02f id:%.02f wa:%.02f hi:%.02f si:%.02f st:%.02f\n",
				s.cpu_usage.cpuName,
				s.cpu_usage.us,
				s.cpu_usage.sy,
				s.cpu_usage.ni,
				s.cpu_usage.id,
				s.cpu_usage.wa,
				s.cpu_usage.hi,
				s.cpu_usage.si,
				s.cpu_usage.st);
		
		printf("mem usage used rate: %.02f\n", s.mem_usage.usedRate);
		printf("mem usage freeram: %ld KB\n", s.mem_usage.freeram);
		printf("mem usage sharedram: %ld KB\n", s.mem_usage.sharedram);
		printf("mem usage bufferram: %ld KB\n", s.mem_usage.bufferram);
		printf("mem usage totalram: %ld KB\n", s.mem_usage.totalram);
		
		printf("disk usage Total:%llu KB;\navail:%llu KB\n",s.disk_use.diskTotal,s.disk_use.diskAvail);
		printf("disk usage used rate:%.02f\n",s.disk_use.useRate);

		if(add_info(&s))
		{
			printf("Add item to db failed!!\n");
			continue;
		}
		
		sleep(ACQ_CYCLE_TIME);
	}
	
	deinit_mysql();
	
	return EXIT_SUCCESS;
}
